package com.turman.blibrary.log;

import static com.turman.blibrary.log.BLogConfig.MAX_LEN;

import android.app.Application;

import androidx.annotation.NonNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 文件打印器
 *
 * @author buobao
 * @since 2024/2/29 9:29
 */
public class BFilePrinter implements BLogPrinter {
    private ExecutorService writerService = Executors.newSingleThreadExecutor();
    private File fileDir; //日志文件缓存目录
    private File logFile; //当前打印的日志文件
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat printSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static BFilePrinter instance;

    private BFilePrinter(Application context) {
        File cacheDir = context.getCacheDir();
        fileDir = new File(cacheDir, "blogs");
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
    }

    public static BFilePrinter getInstance(Application context) {
        if (instance == null) {
            synchronized (BFilePrinter.class) {
                if (instance == null) {
                    instance = new BFilePrinter(context);
                }
            }
        }

        return instance;
    }

    @Override
    public void print(@NonNull BLogConfig config, int level, String tag, @NonNull String content) {
        //处理文件创建逻辑，保证多线程情况下不会重复创建文件
        if (logFile == null) {
            synchronized (BFilePrinter.class) {
                if (logFile == null) {
                    logFile = new File(fileDir, "blog-" + sdf.format(new Date()));
                }
            }
        } else {
            String fileName = sdf.format(new Date());
            if (!logFile.getName().contains(fileName)) {
                synchronized (BFilePrinter.class) {
                    if (!logFile.getName().contains(fileName)) {
                        logFile = new File(fileDir, "blog-" + sdf.format(new Date()));
                    }
                }
            }
        }

        //单线程处理文件写入保证下入不错乱
        writerService.submit(()->{
            int len = content.length();
            int countOfSub = len / MAX_LEN;

            try {
                FileWriter fileWriter = new FileWriter(logFile, true);
                BufferedWriter bufWriter = new BufferedWriter(fileWriter);

                String levelType = "";
                switch (level) {
                    case BLogType.A:
                        levelType = "A";
                        break;
                    case BLogType.E:
                        levelType = "E";
                        break;
                    case BLogType.I:
                        levelType = "I";
                        break;
                    case BLogType.V:
                        levelType = "V";
                        break;
                    case BLogType.W:
                        levelType = "W";
                        break;
                    case BLogType.D:
                        levelType = "D";
                        break;
                    default:
                        levelType = "";
                }

                bufWriter.write(printSdf.format(System.currentTimeMillis()) + "\t" +
                        (config.showThread() ? Thread.currentThread().getName() : "") +
                        "\t" + levelType + "\t" + tag + ":");
                bufWriter.newLine();

                if (countOfSub > 0) {
                    int index = 0;
                    for (int i = 0; i < countOfSub; i++) {
                        bufWriter.write(content.substring(index, index + MAX_LEN));
                        bufWriter.newLine();
                        index += MAX_LEN;
                    }
                    if (index != len) {
                        bufWriter.write(content.substring(index, len));
                        bufWriter.newLine();
                    }
                } else {
                    bufWriter.write(content);
                    bufWriter.newLine();
                }
                bufWriter.close();
                bufWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}


















